package com.elitel.common.utils;

import javax.crypto.Cipher;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

public class RSAUtil {
    private final static String ALGORITHM = "RSA";

    public static void generateKeyPair() throws Exception {
        // 1. 创建 KeyPairGenerator 实例，并指定算法（例如 RSA）
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(ALGORITHM);

        // 2. 初始化密钥对生成器，指定密钥长度（如 2048 位）
        keyPairGen.initialize(2048);

        // 3. 生成密钥对
        KeyPair keyPair = keyPairGen.generateKeyPair();

        // 4. 获取公钥和私钥
        PublicKey publicKey = keyPair.getPublic();
        PrivateKey privateKey = keyPair.getPrivate();

        // 5. 输出密钥（以 Base64 编码打印）
        System.out.println("Public Key:");
        System.out.println(java.util.Base64.getEncoder().encodeToString(publicKey.getEncoded()));

        System.out.println("\nPrivate Key:");
        System.out.println(java.util.Base64.getEncoder().encodeToString(privateKey.getEncoded()));
    }

    public static PublicKey getPublicKey(String publicKey) throws Exception {
        byte[] keyBytes = Base64.getDecoder().decode(publicKey);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
        return keyFactory.generatePublic(keySpec);
    }

    public static String encrypt(String toEncryptStr, String publicKeyStr) throws Exception {
        Cipher encryptCipher = Cipher.getInstance(ALGORITHM);
        encryptCipher.init(Cipher.ENCRYPT_MODE, getPublicKey(publicKeyStr));
        byte[] encryptedBytes = encryptCipher.doFinal(toEncryptStr.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    public static PrivateKey getPrivateKey(String privateKey) throws Exception {
        byte[] keyBytes = Base64.getDecoder().decode(privateKey);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
        return keyFactory.generatePrivate(keySpec);
    }

    public static String decrypt(String toDecryptStr, String privateKeyStr) throws Exception {
        Cipher decryptCipher = Cipher.getInstance(ALGORITHM);
        decryptCipher.init(Cipher.DECRYPT_MODE, getPrivateKey(privateKeyStr));
        byte[] decryptedBytes = decryptCipher.doFinal(Base64.getDecoder().decode(toDecryptStr));
        return new String(decryptedBytes);
    }
}
